import cv2
import matplotlib.pyplot as plt
cv2.ocl.setUseOpenCL(False)

img1 = cv2.imread('../misc_pic/yl01_01.jpg')
img2 = cv2.imread('../misc_pic/yl01_02.jpg')
gray1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
gray2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)

##step 1 detect keypoints & compute descriptor
surf=cv2.xfeatures2d.SURF_create(4000)  #参数为Hessian阀值
kp1, des1 = surf.detectAndCompute(gray1,None)
kp2, des2 = surf.detectAndCompute(gray2,None)

##step 2 特征匹配
FLANN_INDEX_KDTREE=1
indexParams=dict(algorithm =FLANN_INDEX_KDTREE,trees=5)
searchParams=dict(checks=100)
flann=cv2.FlannBasedMatcher(indexParams,searchParams)
matches=flann.knnMatch(des1,des2,k=2)
matches=sorted(matches,key=lambda x:x.distance) #按距离排序

img3=cv2.drawMatches(img1,kp1,img2,kp2,matches[:40],img2,flags=2)

#cv2.imwrite("e:\out.jpg",img3)

plt.imshow(img3);
plt.show()
#cv2.namedWindow("camera", cv2.WINDOW_KEEPRATIO )
#cv2.imshow('camera', img3)
while (True):
    if cv2.waitKey() & 0xff == ord("q"):
        break
cv2.destroyAllWindows()
